<?php

namespace app\savant\controller;

use think\Request;
use think\facade\Log;
use app\common\exception\ZeduException;
use app\common\enums\ResultEnum;
use app\common\model\Article as ArticleModel;
use app\common\utils\ResultVOUtil;
use app\common\model\UserTags;
use app\common\model\ArticleDetail;
use app\common\validate\Article as ArticleValidate;
use app\common\utils\OssFlies;

class Article extends Base
{
    /**
     * 文章列表
     *
     * @return \think\Response
     */
    public function index($search='',$length=10,$page=1)
    {
        $where[] = ['author','=',session('savant.pid')];
        if ( !empty($search) ) {
            $where[] = ['title','like','%'.$search.'%'];
        }
        try {
            $model = ArticleModel::where($where)
                                ->paginate($length,false,[
                                   'type'     => 'bootstrap',
                                   'var_page' => 'page',
                                   'page'=>$page,
                                ]);
       
        } catch (\Exception $e) {
            Log::record('[文章管理]列表:'.$e->getMessage(),'error');
            return ResultVOUtil::error(ResultEnum::ERROR);
        }
        return ResultVOUtil::success($model);
        
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 添加文章
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->param();
        $validate = new ArticleValidate();
        if (!$validate->check($data)) {
            throw new ZeduException(['code'=>ResultEnum::PARAM_ERROR['code'],'msg'=>$validate->getError()]);
        }
        
        if(count($data['cateValue'])>1){
            $data['cid'] = $data['cateValue'][1];
        }else{
            $data['cid'] = $data['cateValue'][0];
        }
        
        if(strpos($data['thumb'],'base64')>0){
            $oss = new OssFlies();
            $url = 'zedu/uploads/aricle/'.date("Ymd").'/'.md5($data['thumb']).'.png';
            $thump = explode(',', $data['thumb']);
            
            $bool = $oss->stringOss('zedu/uploads/'.$url, base64_decode($thump[1]));
            if($bool){
                $data['thumb'] = $url;
            }else{
                return ResultVOUtil::error(ResultEnum::OSS_UPLOAD_ERROR['code'],'上传封面失败');
            }
        }else{
            $data['thumb'] = 'zedu/uploads/aricle/4b439ff01dc4d6ec88af48a56ba04bb7.jpg';
        }
        
        if(count($data['articleTagSelected'])>0){
            //存储到tags表数次数
            $data['tags'] = implode(',', $data['articleTagSelected']);
            try {
                UserTags::whereIn('id',$data['articleTagSelected'])->setInc('count');
            } catch (\Exception $e) {
                Log::record('[文章新增]添加标签:'.$e->getMessage(),'error');
                return ResultVOUtil::error('添加标签失败');
            }
        }
        
        $model = new ArticleModel();
        try {
            $model->startTrans();
            $model->author = session('savant.pid');
            $model->allowField(true)->save($data);
            if($model->id){
                $articleDetail = new ArticleDetail;
                $articleDetail->aid = $model->id;
                $articleDetail->contented = $data['contented'];
                $articleDetail->save();
                
                if($articleDetail->id){
                    $model->commit();
                    return ResultVOUtil::success('添加成功');
                }else{
                    $model->rollback();
                    return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
                }
                
            }else{
                $model->rollback();
                return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
            }
        } catch (\Exception $e) {
            $model->rollback();
            Log::record('[文章管理]新增:'.$e->getMessage(),'error');
            return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
        }
        
    }

    /**
     * 文章详情
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id=1)
    {
        $model = ArticleModel::get($id);
        $model['detail'];
        if($model){
            return ResultVOUtil::success($model);            
        }else{
            return ResultVOUtil::error(ResultEnum::FIND_ERROR['code'],'查询为空');
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
